<?php

namespace app\admin\controller;

use app\api\controller\ExpediaApi;
use app\api\controller\KbxOrder;
use app\api\model\HotelSpu;
use app\api\model\HotelSpuSpec;
use app\api\model\HotelRoomSku;
use app\api\controller\Common;
use \think\Cookie;
use app\api\controller\TeamAmericany;
use app\api\controller\DidaApi;
use app\admin\model\Tahotel;
use app\admin\model\GeoHash;
use think\Exception;
use think\Request;
use think\db;

class Hotel extends User
{
    //************************* TeamAmerica API ******************************************

    //按照城市展示酒店
    public function showHotel(){
        $CityCode = $this->request->has('CityCode') ? $this->request->param('CityCode', '', 'string') : '';
        $post = $this->request->post();

        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post=Cookie::get('postHotelList');
        }else{
            //把条件写入缓存
            Cookie::set('postHotelList',$post);
        }

        $where = [];
        if (isset($post['keywords']) and !empty($post['keywords'])) {
            $where['VendorName'] = ['like', '%' . $post['keywords'] . '%'];
        }

        $GeoHash = new GeoHash();
        if(isset($post['lat']) && isset($post['lng']) && $post['lat']!=='' && $post['lng']!==''){
            $geoCode = $GeoHash->encode($post['lat'],$post['lng']);
            $geoCode = substr($geoCode,0,4);
            $where['geoCode'] = ['like', $geoCode . '%'];
            $hotelData = db("tahotel")->where($where)->select();

            //距离排序
            if(isset($post['lat']) && isset($post['lng']) && $post['lat']!=='' && $post['lng']!==''){
                if(!empty($hotelData)){
                    //算出实际距离
                    foreach($hotelData as $k=>$v) {
                        $distance = $GeoHash->getDistance($post['lat'], $post['lng'], $v['Latitude'], $v['Longitude']);
                        if($distance>1000){
                            $distanceNum = $distance/1000;
                            $hotelData[$k]['distance'] = $distanceNum." km";
                        }else{
                            $hotelData[$k]['distance'] = $distance." m";
                        }
                        //排序列
                        $sortdistance[$k] = $distance;
                    }
                    array_multisort($sortdistance,SORT_ASC,$hotelData);
                }
            }
        }else{
            if($CityCode!=''){
                $where['CityCode'] = $CityCode;
            }
            $Tahotel = new Tahotel();
            $hotelData = $Tahotel->where($where)->order("WebPriority desc")->paginate(20);
            $this->assign('renderFlag', 1);
        }

        if(empty($post)){
            $post = [
                'arrivalDate'=>'',
                'NumberOfRooms'=>1,
                'adult'=>2,
                'child'=>0
            ];
        }

        $this->assign('info', $hotelData);
        $this->assign('CityCode', $CityCode);
        $this->assign('wherelist', $post);

        return $this->fetch();
    }

    //展示价格页
    public function search(){
        $VendorID = $this->request->has('VendorID') ? $this->request->param('VendorID', 0, 'intval') : 0;
        $CityCode = $this->request->has('CityCode') ? $this->request->param('CityCode', '', 'string') : '';
        $arrivalDate = $this->request->has('arrivalDate') ? $this->request->param('arrivalDate', '', 'string') : '';
        $NumberOfRooms = $this->request->has('NumberOfRooms') ? $this->request->param('NumberOfRooms', 0, 'intval') : 0;
        $adult = $this->request->has('adult') ? $this->request->param('adult', 0, 'intval') : 0;
        $child = $this->request->has('child') ? $this->request->param('child', 0, 'intval') : 0;

        $arrivalDate = str_replace("+"," ",$arrivalDate);

        if(!isset($post)){
            $post['arrivalDate'] = $arrivalDate;
            $post['NumberOfRooms'] = $NumberOfRooms;
            $post['adult'] = $adult;
            $post['child'] = $child;
        }

        if($arrivalDate!=='' && $NumberOfRooms>0 && $adult>0){
            $dateArr = explode("~",$arrivalDate);
            $startDate  = $dateArr[0];
            $endDate  = $dateArr[1];
            if($startDate==$endDate){
                $NumberOfNights = 1;
            }else{
                $d1 = strtotime($startDate);
                $d2 = strtotime($endDate);
                $NumberOfNights = round(($d2-$d1)/3600/24);
            }

            $NumberOfNights = intval($NumberOfNights);

            if($adult==1){//Single, Double, Triple, Quad, SGL+1CH, DBL+1CH, DBL+2CH, TPL+1CH
                $Occupancy = $child>0 ? 'SGL+1CH' : 'Single';
            }elseif($adult==2){
                if($child==0){
                    $Occupancy = 'Double';
                }elseif($child==1){
                    $Occupancy = 'DBL+1CH';
                }else{
                    $Occupancy = 'DBL+2CH';
                }
            }elseif($adult==3){
                $Occupancy = $child>0 ? 'TPL+1CH' : 'Triple';
            }else{
                $Occupancy = 'Quad';
            }

            $TeamAmericany = new TeamAmericany();
            $data = $TeamAmericany->PriceSearch($CityCode,$VendorID,$startDate,$Occupancy,$NumberOfNights,$NumberOfRooms);
            if(!empty($data['hotelSearchResponse'])){
                if(!isset($data['hotelSearchResponse']['body']['ProductCode'])){
                    $info = $data['hotelSearchResponse']['body'];
                }else{
                    $info[] = $data['hotelSearchResponse']['body'];
                }

                foreach ($info as $key=>$value){
                    $info[$key]['ProductDetails'] = "";
                    if(!empty($value['TeamVendorID'])){
                        $info[$key]['ProductDetails'] = db('tahotel')->field('concat(VendorId,"-",VendorName,"-",City) as info')->where('VendorId',$value['TeamVendorID'])->find()['info']??'';
                    }
                }

            }else{
                $info = [];
            }
        }else{
            $info= [];
        }

        $this->assign('info', $info);
        $this->assign('VendorID', $VendorID);
        $this->assign('CityCode', $CityCode);
        $this->assign('wherelist', $post);

        return $this->fetch();
    }

    //*************************道旅API******************************************
    //道旅首页
    public function didaIndex(){
        $post = $this->request->param();

        $CityCode = !empty($post['CityName']) ? $post['CityName'] : '';
        $city = db("didacity")->where("CityCode",$CityCode)->field("CityLongName_CN,CityLongName,CityName_CN,CityName")->find();
        $post['CityCode'] = $CityCode;
        $cityNameCN = !empty($city['CityLongName_CN']) ? $city['CityLongName_CN'] : $city['CityName_CN'];
        $cityName = !empty($city['CityLongName']) ? $city['CityLongName'] : $city['CityName'];
        $post['CityName'] = !empty($cityNameCN) ? $cityNameCN."，".$cityName : $cityName;

        $HotelID = !empty($post['HotelName']) ? $post['HotelName'] : '';
        $hotel = db("didahotel")->where("HotelID",$HotelID)->field("Name_CN,Name")->find();
        $post['HotelID'] = $HotelID;
        $post['HotelName'] = !empty($hotel['Name_CN']) ? $hotel['Name_CN']."，".$hotel['Name'] : $hotel['Name'];

        $where = [];
        if(!empty($CityCode)){
            $where['DestinationID'] = $CityCode;
        }
        if(!empty($HotelID)){
            $where['HotelID'] = $HotelID;
        }

        $info = [];
        if(!empty($where)){
            $info = db("didahotel")->where($where)->select();
        }

        $PropertyCategorys = cache("dida_PropertyCategoryList");
        if(empty($PropertyCategorys)){
            $DidaApi = new DidaApi();
            $DidaApi->saveDidaCache();
            $PropertyCategorys = cache("dida_PropertyCategoryList");
        }

        $PKArr = [];
        foreach ($PropertyCategorys['PropertyCategorys'] as $k=>$v) {
            $PKArr[$v['ID']] = !empty($v['Description_CN']) ? $v['Description_CN']."(".$v['Description_EN'].")" : $v['Description_EN'];
        }

        foreach ($info as $k=>$v) {
            $info[$k]['allName'] = !empty($v['Name_CN']) ? $v['Name_CN']."，".$v['Name'] : $v['Name'];
            $info[$k]['allAddress'] = !empty($v['Address_CN']) ? $v['Address_CN']."，".$v['Address'] : $v['Address'];
            if(!empty($v['PropertyCategory'])){
                $info[$k]['PropertyCategoryName'] = $PKArr[$v['PropertyCategory']];
            }
        }

        $this->assign('info', $info);
        $this->assign('wherelist', $post);

        return $this->fetch();
    }

    //模糊查询ajax获取城市列表
    public function getDidaCityList(){
        $post = $this->request->post();
        $CityName = $post['CityName'];

        $where = [];
        $where['CityName|CityName_CN'] = ['like', '%' . $CityName . '%'];
        $where['Type'] = 'Destination';
        $data = db("didacity")
            ->where($where)
            ->limit(10)
            ->select();

        foreach ($data as $k=>$v) {
            if(!empty($v['CityLongName_CN'])){
                $data[$k]['CityName_CN'] = $v['CityLongName_CN'];
            }
            if(!empty($v['CityLongName'])){
                $data[$k]['CityName'] = $v['CityLongName'];
            }
        }

        return $data;
    }

    //模糊查询ajax获取酒店列表
    public function getHotelNameList(){
        $post = $this->request->post();
        $HotelName = $post['HotelName'];

        $where = [];
        $where['Name|Name_CN'] = ['like', '%' . $HotelName . '%'];
        $data = db("didahotel")
            ->where($where)
            ->limit(10)
            ->select();

        return $data;
    }


    //dida查询价格
    public function searchPrice(){
        $post = $this->request->post();
        $DidaApi = new DidaApi();
        $data = [];
        $arrivalDate = $post['arrivalDate'];
        $arrivalDateArr = explode("~",$arrivalDate);
        $data['CheckInDate'] = trim($arrivalDateArr[0]);
        $data['CheckOutDate'] = trim($arrivalDateArr[1]);

        $data['HotelID'] = $post['HotelID'];
        $data['RoomCount'] = $post['NumberOfRooms'];
        $data['AdultCount'] = $post['adult'];
        $data['ChildCount'] = $post['child'];
        if(!empty($post['childAgeArr']) && $post['childAgeArr']!==''){
            $childAgeArr = explode("&",$post['childAgeArr']);
            $childAgeArr_new = [];
            if(!empty($childAgeArr)){
                foreach ($childAgeArr as $k=>$v) {
                    $childAgeArr_new[] = intval($v);
                }
            }
            $data['ChildAgeDetails'] = $childAgeArr_new;
        }else{
            $data['ChildAgeDetails'] = [];
        }

//        $didahotel = db("didahotel")->where('HotelID',$data['HotelID'])->field("Address_CN")->find();
//        $taPriceData = $this->getTaHotelByAddress($didahotel['Address_CN'],$data['CheckInDate'],$data['CheckOutDate'],$data['RoomCount'],$data['AdultCount'],$data['ChildCount']);
//
//        return $taPriceData;


        $priceData = $DidaApi->getLivePrice($data);
        $BedTypeList = cache("dida_BedTypeList");//床型
        $BreakfastTypeList = cache("dida_BreakfastTypeList");//早餐
        $BedTypeArr = [];
        $BreakfastTypeArr = [];
        foreach ($BreakfastTypeList['Breakfasts'] as $k=>$v) {
            $BreakfastTypeArr[$v['ID']] = $v['Name_CN'];
        }
        foreach ($BedTypeList['BedTypes'] as $k=>$v) {
            $BedTypeArr[$v['ID']] = $v['Name_CN'];
        }

        $resData = [];
        if(empty($priceData['RatePlanList'])){
            $resData['msg'] = "未获取到符合条件的酒店";
            return $resData;
        }

        $bedType = 0;
        if(isset($post['bedType']) && $post['bedType']>0){
            $bedType = $post['bedType'];
        }

        $RatePlanList = $priceData['RatePlanList'];
        foreach ($RatePlanList as $k=>$v) {
            $pArr = [];
            $pArr['RatePlanName'] = $v['RatePlanName'];//价格计划Name
            $pArr['RatePlanID'] = $v['RatePlanID'];//RatePlanID
            $pArr['TotalPrice'] = $v['TotalPrice'];//总价
            $pArr['Currency'] = $v['Currency'];//货币
            $pArr['BreakfastType'] = $BreakfastTypeArr[$v['BreakfastType']];//早餐类型
            $pArr['BedType'] = $BedTypeArr[$v['BedType']];//床型
            $pArr['InventoryCount'] = $v['InventoryCount'];//库存
            $pArr['StandardOccupancy'] = $v['StandardOccupancy'];//标准入住人数
            $pArr['MaxOccupancy'] = $v['MaxOccupancy'];//最大入住人数

            //筛选床型
            if($bedType==1){//大床
                if(strstr($pArr['BedType'],"大床")==false){
                    continue;
                }
            }elseif($bedType==2){//双床
                if(strstr($pArr['BedType'],"双床")==false){
                    continue;
                }
            }

            //价格集合  ['StayDate'=>,'Price'=>]  日期，金额
//            $pArr['PriceList'] = $v['PriceList'];
            $pArr['PriceStr'] = '';
            if(!empty($v['PriceList'])){
                foreach ($v['PriceList'] as $k_c=>$v_c) {
                    $pArr['PriceStr'] .= "<div style='width:99%;float:left;'><div style='width:50%;float:left;'>".date("Y-m-d",strtotime($v_c['StayDate']))."</div><div style='width:40%;margin-left:1%;float:left;'>￥".$v_c['Price']."</div></div>";
                }
            }

            //退改规则集合  ['Amount'=>,'FromDate'=>]  罚金，生效日期
//            $pArr['RatePlanCancellationPolicyList'] = $v['RatePlanCancellationPolicyList'];
            $pArr['RatePlanCancellationPolicyStr'] = '';
            if(!empty($v['RatePlanCancellationPolicyList'])){
                $num_c = 1;
                foreach ($v['RatePlanCancellationPolicyList'] as $k_c=>$v_c) {
                    $pArr['RatePlanCancellationPolicyStr'] .= $num_c."、于 ".$v_c['FromDate']." 后取消，将取消收取罚金￥".$v_c['Amount']."元<br>";
                    $num_c++;
                }
            }
            $resData['data'][] = $pArr;
        }
        $resData['msg'] = 'OK';

        return $resData;
    }



    //通过地址获取TeamAmerica接口相同酒店  查询价格
    public function getTaHotelByAddress($address,$startDate,$endDate,$NumberOfRooms,$adult,$child){
        $Address = strtoupper($address);//转换大写
        $taHotelData = db("tahotel")->where("VendorAddress",$Address)->find();
        if(empty($taHotelData)){
            return [];
        }

        if($adult==1){//Single, Double, Triple, Quad, SGL+1CH, DBL+1CH, DBL+2CH, TPL+1CH
            $Occupancy = $child>0 ? 'SGL+1CH' : 'Single';
        }else{
            $Occupancy = 'Single';
        }

        if($startDate==$endDate){
            $NumberOfNights = 1;
        }else{
            $d1 = strtotime($startDate);
            $d2 = strtotime($endDate);
            $NumberOfNights = round(($d2-$d1)/3600/24);
        }
        $NumberOfNights = intval($NumberOfNights);
        $NumberOfRooms = intval($NumberOfRooms);

        $CityCode  = $taHotelData['CityCode'];
        $VendorID = $taHotelData['VendorID'];

        $TeamAmericany = new TeamAmericany();
        $priceData = $TeamAmericany->PriceSearch($CityCode,$VendorID,$startDate,$Occupancy,$NumberOfNights,$NumberOfRooms);

        return $priceData;
    }



    public function getTaPriceTest(){
        $ArrivalDate = "2019-08-08";
        $NumberOfNights = 2;
        $NumberOfRooms = 2;
        $Occupancy  = "Single";
        $CityCode  = "NYC";
        $VendorID = 6300;
        $TeamAmericany = new TeamAmericany();
        $priceData = $TeamAmericany->PriceSearch($CityCode,$VendorID,$ArrivalDate,$Occupancy,$NumberOfNights,$NumberOfRooms);
        $data = $priceData['hotelSearchResponse']['body'];

        $priceData = [];
        foreach ($data as $k=>$v) {
            $pArr = [];
            $pArr['RoomType'] = $v['RoomType'];
            $pArr['NonRefundable'] = $v['NonRefundable'];
            $pArr['MaxOccupancy'] = $v['MaxOccupancy'];
            $pArr['NightlyInfo'] = $v['NightlyInfo'];

        }



        echo "<pre>";
        var_dump($data);
        echo "</pre>";
        exit;
    }
    ////////////////////////////////////////////////20200908新增酒店模型/////////////////////////////////////
    //主页面
    public function index(){
        $post = $this->request->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post=Cookie::get('hotelParams');
        }else{
            //把条件写入缓存
            Cookie::set('hotelParams',$post);
        }

        $where = [];
        if (isset($post['keywords']) and !empty($post['keywords'])) {
            $where['hotel_id|name|address|city_name'] = ['like', '%' . trim($post['keywords']) . '%'];
        }

        if (isset($post['city_id']) and $post['city_id']!=='') {
            $where['city_id'] = $post['city_id'];
        }
        //获取 hotel 列表
        $offset = 20;
        $list = (new HotelSpu())->getAdminHotelList($where,$offset);
        foreach ($list as $key=>$value){
            $list[$key]['goods_id'] = 0;
            if($value['channel']=='teamAmerica'){
                $list[$key]['details'] = db('tahotel')->where('VendorId',$value['source_id'])->find();
            }elseif($value['channel']=='dida'){
                $list[$key]['details'] = db('didahotel')->where('HotelId',$value['source_id'])->find();
            }else{
                $list[$key]['details'] = new \ArrayObject();
            }
        }
        $this->assign('list', $list);
        $this->assign('hotelParams', $post);
        $cityList = (new HotelSpu())->getCityList();
        $this->assign('cityList', $cityList);

        return $this->fetch();
    }
    //新增酒店模型
    public function addNewHotel(Request $request)
    {
        if($request->isPost()){
            if(empty($request->post('id'))){
                //新增
                db::startTrans();
                try{
                    $msg = (new HotelSpu())->createHotel($request->post());
                    if(!empty($msg)){
                        db::rollback();
                        return $this->error($msg);

                    }else{
                        db::commit();
                        return $this->success('创建成功');
                    }
                }catch(Exception $e){
                    db::rollback();
                    return $this->error($e->getMessage());
                }

            }else{
               //更新
                db::startTrans();
                try{
                    $msg = (new HotelSpu())->updateHotel($request->post());
                    if(!empty($msg)){
                        db::rollback();
                        return $this->error($msg);
                    }else{
                        db::commit();
                        return $this->success('更新成功');
                    }
                }catch(Exception $e){
                    db::rollback();
                    return $this->error($e->getMessage());
                }

            }
        }

        if($request->param('id') && $id = $request->param('id')){
            $details = (new HotelSpu())->getHotelDetail($id);
            $this->assign('details',$details);

            $sourceList = (new HotelSpu())->getThirdHotelList($details['channel']);
            $this->assign('sourceList',$sourceList);
        }
        //星级参数
        $levels = (new HotelSpu())->getHotelLevels();
        $this->assign('levels',$levels);
        $cityList = (new HotelSpu())->getCityList();
        $this->assign('cityList', $cityList);
        $channelList = (new HotelSpu())->getChannelList();
        $this->assign('channelList', $channelList);
        //直接渲染数据
        return $this->fetch();
    }

    //删除酒店
    public function delHotel(Request $request)
    {
        if(!$request->isPost()){
            return $this->error('请以POST方式提交!');
        }
        if(empty($request->param('id'))){
            return $this->error('请求参数错误!');
        }

        $details = (new HotelSpu())->getHotelDetail($request->param('id'));
        if(empty($details)){
            return $this->error('酒店信息不存在!');
        }

        $res = (new HotelSpu())->delHotel($request->param('id'));
        if(false === $res){
            return $this->error('删除失败!');
        }else{
            return $this->success('删除成功!');
        }
    }

    //设置房间信息 sku
    public function setRoomSku(Request $request)
    {
        if($request->isPost()){
            if($request->post('hotel_id')){
                $res_msg = (new HotelRoomSku())->createRoomSkus($request->post());
                if(!empty($res_msg)){
                    return $this->error($res_msg);
                }else{
                    return $this->success('创建成功');
                }
            }else{
                return $this->error('请求参数错误！');
            }
        }
        $id = $request->param('id',0);
        if(empty($id)) return $this->error('请求参数错误！');
        $table_name = ['规格名称','库存','最低下单数','最小增长数'];
        $details = (new HotelSpu())->getHotelDetail($id);
        $this->assign('details',$details);
        $this->assign('table_name',$table_name);
        //获取规格
        $spec_where['hotel_id'] = ['in',[0,$id]];
        $specs = (new HotelSpuSpec())->getAdminHotelSpecList($spec_where);
        $this->assign('specs',$specs);

        return $this->fetch();
    }
    //设置房间价格 sku_price
    public function setRoomSkuPrice(Request $request)
    {
        $id = $request->param('id',0);
        if(empty($id)) return $this->error('请求参数错误！');
        $table_name = ['规格名称','库存','最低下单数','最小增长数'];
        $details = (new HotelSpu())->getHotelDetail($id);
        if(empty($details['sales_start_day'])) $details['sales_start_day'] = time();
        if(empty($details['sales_end_day'])) $details['sales_end_day'] = strtotime('+2 years');
        $this->assign('details',$details);
        $roomSkus = (new HotelRoomSku())->getRoomSkusByHotelId($id);
        $this->assign('roomSkus',$roomSkus);
        $this->assign('table_name',$table_name);

        //货币
        $currency = !empty($details['currency'])?db('city')->where('currency_code',$details['currency'])->find():[];
        $details['currency_symbol'] = !empty($currency)?$currency['currency_symbol']:'￥';
        //获取货币类型列表
        $currencyCodeList = (new Common())->getCurrencyListByCity();
        foreach ($currencyCodeList as $key=>$value){
            $currencyCodeList[$key]['currency_all_name'] = $value['currency_name'].'('.$value['currency_code'].')';
        }
        $this->assign("currencyCodeList",$currencyCodeList);

        return $this->fetch();
    }

    public function setBasePackage(){
        $id = input('id',0);
        if(empty($id)) return $this->error('参数有误');
        $product = db('product')->find($id);
        //货币
        $currency = !empty($product['currency'])?db('city')->where('currency_code',$product['currency'])->find():[];
        $product['currency_symbol'] = !empty($currency)?$currency['currency_symbol']:'￥';
        //套餐
        $packageList =	db('product_base_package')->where('product_id',$id)->where('status',1)->select();
        $this->assign('product_id',$id);
        $product['currency'] = !empty($product['currency'])?$product['currency']:"CNY";
        $this->assign('product',$product);
        $this->assign('packageList',$packageList);
        //获取货币类型列表
        $currencyCodeList = (new Common())->getCurrencyListByCity();
        foreach ($currencyCodeList as $key=>$value){
            $currencyCodeList[$key]['currency_all_name'] = $value['currency_name'].'('.$value['currency_code'].')';
        }
        $this->assign("currencyCodeList",$currencyCodeList);
        return $this->fetch();
    }

    public function ajaxUpdateHotelSalesTime(Request $request)
    {
        if(!$request->isPost()){
            return $this->error('请以POST方式提交！');
        }
        if(!$request->post('id')){
            return $this->error('请求参数错误！');
        }
        $updateData = [];
        if(!empty($request->post('currency'))) $updateData['currency'] = $request->post('currency');
        if(!empty($request->post('sales_start_day'))) $updateData['sales_start_day'] = strtotime($request->post('sales_start_day'));
        if(!empty($request->post('sales_end_day'))) $updateData['sales_end_day'] = strtotime($request->post('sales_end_day'));
        $res = db('hotel_spu')->where('hotel_id',$request->post('id'))->update($updateData);

        if(false === $res){
            return $this->error('更新失败！');
        }else{
            return $this->success('更新成功！');
        }
    }

    public function hotelSpec(Request $request)
    {
        //获取 hotel 列表
        if($request->isPost()){
            //条件从缓存取出
            $post = $request->post();
        }else{
            $post = Cookie::get('hotelSpecParams');
        }
        $where = [];
        if(!empty($post['keywords'])){
            $where['id|spec_name'] = ['like','%'.$post['keywords'].'%'];
        }
        if(!empty($post['hotel_id']) || $post['hotel_id']==='0'){
            $where['hotel_id'] = $post['hotel_id'];
        }
        $list = (new HotelSpuSpec())->getAdminHotelSpecList($where,999);
        foreach ($list as $key=>$value){
            $list[$key]['attr_json'] = !empty($value['attr_json'])?json_decode($value['attr_json'],true):[];
        }
        $this->assign('list', $list);
        $this->assign('hotelParams', $post);
        $hotelList = (new HotelSpu())->getAdminHotelList([],999);
        $this->assign('hotelList', $hotelList);
        $this->assign('hotelSpecParams', $post);

        return $this->fetch();
    }

    //创建酒店规格
    public function addNewHotelSpec(Request $request)
    {
        if($request->isPost()){
            if(empty($request->post('id'))){
                //新增
                db::startTrans();
                try{
                    $msg = (new HotelSpuSpec())->createHotelSpec($request->post());
                    if(!empty($msg)){
                        db::rollback();
                        return $this->error($msg);
                    }else{
                        db::commit();
                        return $this->success('创建成功');
                    }
                }catch(Exception $e){
                    db::rollback();
                    return $this->error($e->getMessage());
                }
            }else{
                //更新
                db::startTrans();
                try{
                    $msg = (new HotelSpuSpec())->updateHotelSpec($request->post());
                    if(!empty($msg)){
                        db::rollback();
                        return $this->error($msg);
                    }else{
                        db::commit();
                        return $this->success('更新成功');
                    }
                }catch(Exception $e){
                    db::rollback();
                    return $this->error($e->getMessage());
                }

            }
        }

        if($request->param('id') && $id = $request->param('id')){
            $details = (new HotelSpuSpec())->getHotelSpecDetail($id);
            $this->assign('details',$details);
        }
        //星级参数
        $attrs = (new HotelSpuSpec())->getHotelSpuAttrs();
        $this->assign('attrs', $attrs);
        //酒店列表
        $hotelList = (new HotelSpu())->getAdminHotelList();
        $this->assign('hotelList', $hotelList);
        //直接渲染数据
        return $this->fetch();
    }
    //删除酒店规格
    public function delHotelSpec(Request $request)
    {
        if(!$request->isPost()){
            return $this->error('请以POST方式提交！');
        }
        $id = $request->param('id',0);
        if(!$request->post('id')){
            return $this->error('请求参数错误！');
        }
        $details = (new HotelSpuSpec())->getHotelSpecDetail($id);
        if(empty($details)){
            return $this->error('规格不存在！');
        }
        if($details['hotel_id']==0){
            return $this->error('通用规格不允许删除！');
        }

        $res = (new HotelSpuSpec())->delHotelSpec($id);
        if(false === $res){
            return $this->error('删除失败！');
        }else{
            return $this->success('删除成功！');
        }
    }

    public function ajaxSetRoomSkuPrice(Request $request)
    {
        if($request->isPost()){
            if(empty($request->post('hotelId'))) return $this->error('缺少hotelId参数');
            if(empty($request->post('date/a'))) return $this->error('缺少date参数');
            if(empty($request->post('price/a'))) return $this->error('缺少price参数');

            $hotelId = $request->post('hotelId');
            $date = $request->post('date/a');
            $price = $request->post('price/a');
            $insertData = [];
            db::startTrans();
            try{
                foreach ($date as $value){
                    foreach ($price as $p_value){
                        $insertData[] = [
                            'hotel_id'=>$hotelId,
                            'room_id'=>$p_value['room_id'],
                            'cost_price'=>$p_value['cost_price'],
                            'sales_price'=>$p_value['sales_price'],
                            'market_price'=>$p_value['market_price'],
                            'stock'=>$p_value['stock'],
                            'create_time'=>time(),
                            'update_time'=>time(),
                            'stay_day'=>$value,
                        ];
                    }
                }
//                var_dump($insertData);exit;
                if(!empty($insertData)){
                    db('hotel_room_sku_price')->insertAll($insertData);
                }
                //更新酒店的价格
                $this->updateHotelPrice($hotelId);
                db::commit();
                return $this->success('设置成功！');
            }catch(Exception $e){
                db::rollback();
                return $this->error($e->getMessage());
            }

        }else{
            return $this->error('请以POST方式提交');
        }
    }

    public function updateHotelPrice($hotelId)
    {
        $price = db('hotel_room_sku_price')
            ->where(['hotel_id'=>$hotelId,'sales_price'=>['gt',0],'market_price'=>['gt',0]])
            ->field('min(sales_price) as sales_price,min(market_price) as market_price')->group('hotel_id')->find();
        if(!empty($price)){
            db('hotel_spu')->where('hotel_id',$hotelId)->update(['sales_price'=>$price['sales_price'],'market_price'=>$price['market_price']]);
        }
    }

    public function getHotelDailypriceByMonth($year,$month,$hotel_id)
    {
        $month_value = $month>9?$month:"0".$month;
        $start_day = $year.'-'.$month_value.'-01';
        if($month>=12){
            $year+=1;$month_value="01";
        }else{
            $month+=1;
            $month_value = $month>9?$month:"0".$month;
        }
        $end_day = $year.'-'.$month_value.'-01';
        //大于等于start_day 小于end_day
        $base_dailyprice = db('hotel_room_sku_price')->where([
            'hotel_id'=>$hotel_id,
            'stay_day'=>['between',[$start_day,$end_day]],
            'cost_price'=>['gt',0],
            'sales_price'=>['gt',0],
        ])->field('stay_day,min(cost_price) as cost_price,min(sales_price) as sales_price')->group('stay_day')->select();
        //var_dump(db()->getLastSql());
        $this->success('success','',$base_dailyprice);
    }

    //通过hotel_id获取售卖月份
    public function getSaleMonthByHotelId($hotel_id)
    {
        if(empty($hotel_id)) return $this->error('fail');
        //大于等于start_day 小于end_day
        $base_daily_date= db('hotel_room_sku_price')->where([
            'hotel_id'=>$hotel_id
        ])->group('stay_day')->column('stay_day');
        $months = [];
        $dateArr = [];
        foreach ($base_daily_date as $value){
            $show_date = date("Y年m月",strtotime($value));
            $year = date("Y",strtotime($value));
            $month = date("m",strtotime($value));
            if(!in_array($show_date,$months)){
                $months[] = $show_date;
                $dateArr[] = ['show_date'=>$show_date,'year'=>$year,'month'=>$month];
            }
        }
        //var_dump(db()->getLastSql());
        $this->success('success','',$dateArr);
    }

    //通过package_id和month获取售卖价格
    public function getSalePriceByHotelIdAndMonth($hotel_id,$year,$month)
    {

        if(empty($hotel_id) || $hotel_id < 1) return $this->error('fail');
        if(empty($year) || empty($month)) return $this->error('fail');
        $year = intval($year);
        $month = intval($month);
        $month_value = $month>9?$month:"0".$month;
        $start_day = $year.'-'.$month_value.'-01';
        if($month>=12){
            $year+=1;$month_value="01";
        }else{
            $month+=1;
            $month_value = $month>9?$month:"0".$month;
        }
        $end_day = $year.'-'.$month_value.'-01';
        //大于等于start_day 小于end_day
        $base_dailyprice = db('hotel_room_sku_price')->where([
            'hotel_id'=>$hotel_id,
            'stay_day'=>[['between',[$start_day,$end_day]],['lt',$end_day]]
        ])->field('stay_day,min(cost_price) as cost_price,min(sales_price) as sales_price')->group('stay_day')->select();
//        var_dump(db()->getLastSql());
        $this->success('success','',$base_dailyprice);
    }

    //根据日期获取套餐信息
    public function getHotelDailypriceByDate($hotel_id,$date)
    {
        //大于等于start_day 小于end_day
        $base_dailyprice = db('hotel_room_sku_price p')
            ->join('hotel_room_sku s','p.room_id=s.id','left')
            ->field('p.*,s.name')
            ->where([
                'p.hotel_id'=>$hotel_id,
                'p.stay_day'=>$date
            ])->select();
        //var_dump(db()->getLastSql());
        $this->success('success','',$base_dailyprice);
    }

    //单独设置某天的价格
    public function setSingleDayBasePrice($id,$cost_price,$sales_price,$market_price,$stock)
    {
        $dailyprice = db("hotel_room_sku_price")->find($id);
        if(empty($dailyprice)) return $this->error("修改失败");
        db::startTrans();
        try{
            db("hotel_room_sku_price")->where('id',$id)->update([
                'cost_price'=>$cost_price,
                'sales_price'=>$sales_price,
                'market_price'=>$market_price,
                'stock'=>$stock,
            ]);
            //更新价格区间
            $this->updateHotelPrice($dailyprice['hotel_id']);
            db::commit();
            return json(['code'=>200,'msg'=>'修改成功']);
        }catch (Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'修改失败,原因是'.$e->getMessage()]);
        }
    }

    //根据所选日期删除价格日历
    public function delHotelPriceByDate()
    {
        $post = request()->post();
        $hotel_id = $post['hotel_id']??0;
        $start_time = $post['start_time']??'';
        $end_time = $post['end_time']??'';
        $room_ids = $post['room_ids']??[];

        $hotel_skpu = db('hotel_spu')->find($hotel_id);
        if(empty($hotel_id) || empty($hotel_skpu)) return $this->error('酒店信息错误');

        if(empty($start_time) || empty($end_time)) return $this->error('日期选择错误');
        if(empty($room_ids)) return $this->error('请选择房间SKU');

        db::startTrans();
        try{

            db('hotel_room_sku_price')->where([
                'hotel_id'=>$hotel_id,
                'room_id'=>['in',$room_ids],
                'stay_day'=>[['egt',$start_time],['elt',$end_time]]
            ])->delete();

            //更新价格区间
            $this->updateHotelPrice($hotel_id);
            db::commit();
            return $this->success('删除成功');
        }catch(Exception $e){
            db::rollback();
            return $this->error('删除失败,'.Lang::get('原因是').$e->getMessage());
        }

    }

    public function getHotelSpuDetail($hotel_id)
    {
        $details = (new HotelSpu())->getHotelDetail($hotel_id);
        return $this->result($details,200,'success','json');
    }

    public function addNewHotelAttr(Request $request)
    {
        if($request->isPost()){
            $postData = $request->post();
            if(empty($postData['attrName'])){
                return $this->error('请填写属性名称!');
            }
            if(empty($postData['attrValues/a'])){
                return $this->error('请填写属性可选项!');
            }
            $attrName = $request->post('attrName');
            $attrEnName = $request->post('attrEnName');
            $attrValues = $request->post('attrValues/a');
            $attr = db('hotel_spu_attr')->where('attr_name',$attrName)->find();
            db::startTrans();
            try{
                if(!empty($attr['id'])){
                    $attr_id = $attr['id'];
                }else{
                    db('hotel_spu_attr')->insert([
                        'attr_name'=>$attrName,
                        'attr_en_name'=>$attrEnName,
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ]);
                    $attr_id = db()->getLastInsID();
                }
                $insertData = [];
                //$attrValueExist =  db('hotel_spu_attr_value')->where(['attr_value'=>['in',$attrValues]])->column('attr_value');
                foreach ($attrValues as $value){
                    //if(!empty($attrValueExist) && in_array($value,$attrValueExist)) continue;
                    $insertData[] = [
                        'attr_id'=>$attr_id,
                        'attr_value'=>$value,
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ];
                }
                if(!empty($insertData)){
                    db('hotel_spu_attr_value')->insertAll($insertData);
                }
                db::commit();
                return $this->success('创建成功!');
            }catch (Exception $e){
                db::rollback();
                return $this->error('创建失败!'.$e->getMessage());
            }

        }

        return $this->fetch();
    }

    public function getThirdHotelList($channel)
    {
        if(empty($channel)) return $this->error('请选择渠道！');

        $result = (new HotelSpu())->getThirdHotelList($channel);

        return $this->success('success','',$result);
    }

    public function getThirdHotelDetails($channel,$id)
    {
        if(empty($channel)) return $this->error('请选择渠道！');
        if(empty($id)) return $this->error('请选择关联酒店！');

        $result = (new HotelSpu())->getThirdHotelDetails($channel,$id);

        return $this->success('success','',$result);
    }

    //***************************接入酒店查询***************************//
    //查询条件集合如下
    //id=1267&regionId=178237&keywords=北京&checkIn=2020-05-01&checkOut=2020-05-03&occupancy=2|2-4,9&price_range=&star_level=
    public function searchTripMakeHotel(Request $request)
    {
        $tripMakeId = $request->param('id',0);
        if(empty($tripMakeId)) $this->error('请先创建定制为行程！');
        //获取出行信息
        $tripInfo = db('trip')->field('start_go_time,adult,child')->find($tripMakeId);
        //获取出行人信息
        $tripCustomerInfo = db("tripcustomer")->where(["tripid"=>$tripMakeId])->find();
        $tripCustomerInfo['checkIn'] = $tripInfo['start_go_time'] < time() ?
            date('Y-m-d') : date('Y-m-d',$tripInfo['start_go_time']);
        $tripCustomerInfo['checkOut'] = date('Y-m-d',
            strtotime('+1 day',strtotime($tripCustomerInfo['checkIn'])));
        $tripCustomerInfo['adult'] = $tripInfo['adult'] ?? 1;
        //筛选符合条件的hotels
        $filterArray = ['regionId','checkIn','checkOut','occupancy','price_range','star_level'];
        $params = $request->param();
        $occupancyData = [];
        if(array_key_exists('occupancy',$params)){
            $totalPerson = 0;
            $rooms = [];
            $occupancyData = explode('|',$params['occupancy']);
            foreach ($occupancyData as $occupancy_v){
                $occupancy = explode('-',$occupancy_v);
                $totalPerson += $occupancy[0];
                $childAges = [];
                if(count($occupancy) > 1){
                    $childAges = explode(',',$occupancy[1]);
                    $totalPerson += count($childAges);
                }
                $rooms[] = ['adult'=>$occupancy[0],'child'=>count($childAges),'childAges'=>$childAges];
            }
            $occupancy_json = [
                'roomCount'=>count($occupancyData),
                'totalPerson'=>$totalPerson,
                'rooms'=>$rooms,
            ];
        }else{
            $occupancy_json = [
                'roomCount'=>1,
                'totalPerson'=>1,
                'rooms'=>[
                    ['adult'=>1,'child'=>0,'childAges'=>[]]
                ],
            ];
        }
        $params['occupancy_json'] = json_encode($occupancy_json);
        $this->assign(compact('params'));
        //请求订单接口时 将数据分开
        $params['occupancy'] = $occupancyData;
        foreach ($params as $p_key=>$p_value){
            if(!in_array($p_key,$filterArray)) unset($params[$p_key]);
        }
        $categories = $themes = $combinedAmenities = $barrierFreeFacilities = [];
        if(!empty($params['categories'])) $categories = array_keys($params['categories']);
        if(!empty($params['themes'])) $categories = array_keys($params['themes']);
        if(!empty($params['amenities'])) $combinedAmenities = array_keys($params['amenities']);
        if(!empty($params['barrierFreeFacilities'])) $barrierFreeFacilities = array_keys($params['barrierFreeFacilities']);
        $ratingMin = $params['ratingMin'] ?? 0;
        $ratingMax = $params['ratingMax'] ?? 5;
        $ratingGuestMin = $params['ratingGuestMin'] ?? 0;
        $ratingGuestMax = $params['ratingGuestMax'] ?? 5;
        $params['filter'] = [
            "ratingMax"=> $ratingMax,
            "ratingMin"=>$ratingMin,
            "ratingGuestMin"=>$ratingGuestMin,
            "ratingGuestMax"=>$ratingGuestMax,
            "categories"=>$categories,
            "themes"=>$themes,
            "combinedAmenities"=>$combinedAmenities,
            "barrierFreeFacilities"=>$barrierFreeFacilities,
        ];
        $list = (new KbxOrder())->searchHotelsByRegion($params);
        $list = empty($list['msg'])||($list['code']!=200)?[]:$list['msg'];
        $this->assign(compact('list'));
        return $this->fetch();
    }

    public function tripMakeHotelInfo(Request $request)
    {
        $tripMakeId = $request->param('id',0);
        if(empty($tripMakeId)){
            $tripActiveId = $request->param('aid',0);
            if(empty($tripActiveId)) return $this->error('请先创建定制为行程！');
            $tripSechduleId = db('active')->where(['id'=>$tripActiveId])->field('groupid')->find()['groupid'] ?? 0;
            if(empty($tripSechduleId)) return $this->error('请先创建定制为行程！');
            $tripMakeId = db('schedule')->where(['id'=>$tripSechduleId])->field('groupid')->find()['groupid'] ?? 0;
            if(empty($tripMakeId)) return $this->error('请先创建定制为行程！');
        }
        //获取出行信息
        $tripInfo = db('trip')->field('name,start_go_time,adult,child')->find($tripMakeId);
        //获取出行人信息
        $tripCustomerInfo = db("tripcustomer")->where(["tripid"=>$tripMakeId])->find();
        $tripCustomerInfo['checkIn'] = $tripInfo['start_go_time'] < time() ?
            date('Y-m-d') : date('Y-m-d',$tripInfo['start_go_time']);
        $tripCustomerInfo['checkOut'] = date('Y-m-d',
            strtotime('+1 day',strtotime($tripCustomerInfo['checkIn'])));
        $tripCustomerInfo['adult'] = $tripInfo['adult'] ?? 1;

        $hotelId = $request->param('hid',0);
        if(empty($hotelId)) $this->error('请选择匹配的酒店ID！');

        //筛选符合条件的hotels
        $filterArray = ['propertyId','checkIn','checkOut','occupancy'];
        $params = $request->param();
        $checkIn = !empty($params['checkIn'])?$params['checkIn']:$tripCustomerInfo['checkIn'];
        $checkOut = !empty($params['checkOut'])?$params['checkOut']:$tripCustomerInfo['checkOut'];
        $occupancy = !empty($params['occupancy'])?explode('|',$params['occupancy']):[$tripCustomerInfo['adult']];
        $params = [
            'propertyId'=>$hotelId,
            'checkIn'=>$checkIn,
            'checkOut'=>$checkOut,
            'occupancy'=>$occupancy,
        ];
        foreach ($params as $p_key=>$p_value){
            if(!in_array($p_key,$filterArray)) unset($params[$p_key]);
        }
        $hotelInfo = (new KbxOrder())->getHotelDetails($params);
        if(empty($hotelInfo['msg']) || $hotelInfo['code']!=200){
            return $this->result([],0,'获取酒店信息失败','json');
        }else{
            $hotelInfo = $hotelInfo['msg'];
        }
        $hotelInfo['showTags'] = (new ExpediaApi())->formatHotelTags($hotelInfo);
        $roomData = $hotelInfo['rooms'];
        $this->assign(compact('tripInfo','tripCustomerInfo','hotelInfo','roomData'));
        return $this->fetch();
    }

}